<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!--<el-form-item label="项目编号" prop="projectCode">-->
      <!--  <el-input-->
      <!--      v-model="queryParams.projectCode"-->
      <!--      placeholder="请输入项目编号"-->
      <!--      clearable-->
      <!--      @keyup.enter="handleQuery"-->
      <!--  />-->
      <!--</el-form-item>-->

      <el-row>
        <el-col :span="4.5">
          <el-form-item label="项目编号" prop="projectCode">
            <el-select v-model="queryParams.projectCode" filterable placeholder="请输入或选择项目编号" style="width: 200px;">
              <el-option
                  v-for="item in projectOptions"
                  :key="item"
                  :label="item"
                  :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 下拉框+模糊搜索 -->
        <el-col :span="4.4">
          <el-form-item label="间接明细名" prop="nameId" label-width="100px">
            <el-select v-model="queryParams.nameId" placeholder="请选择间接明细名" clearable style="width: 170px;">
              <el-option
                  v-for="dict in name_id"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="4">
          <el-form-item label="期数" prop="number">
            <el-input
                v-model="queryParams.number"
                placeholder="请输入期数"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4">
          <el-form-item label="创建人" prop="createBy">
            <el-input
                v-model="queryParams.createBy"
                placeholder="请输入创建人"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="创建时间">
            <el-date-picker
                v-model="daterangeCreateTime"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="更新人" prop="updateBy">
            <el-input
                v-model="queryParams.updateBy"
                placeholder="请输入更新人"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="更新时间">
            <el-date-picker
                v-model="daterangeUpdateTime"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:indirect:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:indirect:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:indirect:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:indirect:export']"
            v-if="false">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="indirectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" prop="id" v-if="false" />
      <el-table-column align="center" prop="areaId" v-if="false" />
      <el-table-column label="项目编号" align="center" prop="projectCode" />
      <el-table-column label="间接明细名" align="center" prop="nameId">
        <template #default="scope">
          <dict-tag :options="name_id" :value="scope.row.nameId"/>
        </template>
      </el-table-column>
      <el-table-column label="施工借方发生额合计" align="center" prop="totalNoTax" />
      <el-table-column label="已收账款" align="center" prop="received" />
      <el-table-column label="累计已发生成本" align="center" prop="realTotalWithTax" />
      <el-table-column label="预计总成本" align="center" prop="contractWithTax" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" sortable/>
      <el-table-column label="更新人" align="center" prop="updateBy" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180" sortable>
        <!--<template #default="scope">-->
        <!--  <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>-->
        <!--</template>-->
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:indirect:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:indirect:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改间接费用对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="indirectRef" :model="form" :rules="rules" label-width="80px">

        <!-- 下拉框+模糊搜索 -->
        <el-form-item label="项目编号" prop="projectCode" label-width="140px">
          <el-select v-model="form.projectCode" filterable placeholder="请输入或选择项目编号">
            <el-option
                v-for="item in projectOptions"
                :key="item"
                :label="item"
                :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="期数" prop="number" label-width="140px">
          <el-input-number v-model="form.number" placeholder="期" step-strictly />
        </el-form-item>
        <el-form-item label="间接明细名" prop="nameId" label-width="140px">
          <el-select v-model="form.nameId" placeholder="请选择间接明细名">
            <el-option
                v-for="dict in name_id"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="施工借方发生额合计" prop="totalNoTax" label-width="140px">
          <el-input v-model="form.totalNoTax" placeholder="请输入账面工程施工借方发生额合计" />
        </el-form-item>
        <el-form-item label="已收账款" prop="received" label-width="140px">
          <el-input v-model="form.received" placeholder="请输入已收账款" />
        </el-form-item>
        <el-form-item label="累计已发生成本" prop="realTotalWithTax" label-width="140px">
          <el-input v-model="form.realTotalWithTax" placeholder="请输入累计已发生成本" />
        </el-form-item>
        <el-form-item label="预计总成本" prop="contractWithTax" label-width="140px">
          <el-input v-model="form.contractWithTax" placeholder="请输入预计总成本" />
        </el-form-item>
        <el-form-item label="备注" prop="remark" label-width="140px">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Indirect">
import { listIndirect, getIndirect, delIndirect, addIndirect, updateIndirect } from "@/api/system/indirect";

const { proxy } = getCurrentInstance();
const { name_id } = proxy.useDict('name_id');

const indirectList = ref([]);
const projectOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreateTime = ref([]);
const daterangeUpdateTime = ref([]);

// 获取当前 URL 中的查询参数部分
const queryString = window.location.search;
// 使用 URLSearchParams 对象解析查询参数
const urlParams = new URLSearchParams(queryString);


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectCode: null,
    nameId: null,
    totalNoTax: null,
    received: null,
    realTotalWithTax: null,
    contractWithTax: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    number: null,
    areaId: urlParams.get('areaId')
  },
  rules: {
    projectCode: [
      { required: true, message: "项目编号不能为空", trigger: "blur" }
    ],
    nameId: [
      { required: true, message: "间接明细名不能为空", trigger: "blur" }
    ],
    number: [
      { required: true, message: '请输入或选择期数', trigger: 'blur'},
      { pattern: /^[1-9]\d*$/, message: '期数不可小于1', trigger: 'blur'}
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);


/** 查询间接费用列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  console.log("areaId: " + queryParams.value.areaId);
  queryParams.value.params["areaId"] = queryParams.value.areaId;
  console.log("name_id:" + queryParams.nameId)
  if (null != daterangeCreateTime && '' !== daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  if (null != daterangeUpdateTime && '' !== daterangeUpdateTime) {
    queryParams.value.params["beginUpdateTime"] = daterangeUpdateTime.value[0];
    queryParams.value.params["endUpdateTime"] = daterangeUpdateTime.value[1];
  }
  listIndirect(queryParams.value).then(response => {
    indirectList.value = response.dataList.rows;
    projectOptions.value = response.projectCodeList;
    total.value = response.dataList.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    projectCode: null,
    nameId: null,
    totalNoTax: null,
    received: null,
    realTotalWithTax: null,
    contractWithTax: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    number: 1
  };
  proxy.resetForm("indirectRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = [];
  daterangeUpdateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.areaId = queryParams.value.areaId;
  open.value = true;
  title.value = "添加间接费用";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getIndirect(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改间接费用";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["indirectRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateIndirect(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addIndirect(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除间接费用编号为"' + _ids + '"的数据项？').then(function() {
    return delIndirect(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/indirect/export', {
    ...queryParams.value
  }, `indirect_${new Date().getTime()}.xlsx`)
}

getList();
</script>


